package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.ConfigurationManager;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.SpeechManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Vibrator;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;


/******************
 * @author Sarah
 * 
 *  ------------------
 * |   A    |    B    |
 *  ------------------
 * |                  |
 * |                  |
 * |                  |
 * |                  |
 * -------------------- 
 * |   C    |    D    |
 * --------------------
 *
 */


public class BaseActivity extends Activity {//implements OnGestureListener, OnDoubleTapListener{
	private static final String TAG = BaseActivity.class.getSimpleName();
	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.BaseActivity.SHOW";

	Context context;
	LayoutInflater inflater;
	
	View baseView;
	private Boolean firstTime = true;
	public Boolean passBy = false;
	Button A;
	Button B;
	Button C;
	Button D;
	Rect ARect; 
	Rect BRect;
	Rect CRect;
	Rect DRect;
	public BaseViewListener listener;
	private SpeechManager speechManager;
	private Vibrator vibrator;
	private ConfigurationManager configurationManager;
	
	public Boolean sentResult = false;
	int offset = 0; 

	private GestureDetector gestureDetector;
	private SimpleOnGestureListener gestureListener;
	private Button lastButton = null;

	public void Init(Context c) {

		Log.d(TAG, "Init");

		context = c;

		speechManager = SpeechManager.getInstance(context);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		configurationManager = ConfigurationManager.getInstance(getApplicationContext());
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		baseView = inflater.inflate(R.layout.base, null);

		//gestureScanner = new GestureDetector(context, this);
		//gestureScanner.setOnDoubleTapListener(this);

		gestureListener = new MyGestureDetector();
		gestureDetector = new GestureDetector(context, gestureListener);
		gestureDetector.setOnDoubleTapListener(gestureListener);

		A = (Button) baseView.findViewById(R.id.view_A);
		B = (Button) baseView.findViewById(R.id.view_B);
		C = (Button) baseView.findViewById(R.id.view_C);
		D = (Button) baseView.findViewById(R.id.view_D);

		listener = new BaseViewListener();

		//baseView.setOnTouchListener(listener);

		A.setOnTouchListener(listener);
		B.setOnTouchListener(listener);
		C.setOnTouchListener(listener);
		D.setOnTouchListener(listener);

	}

	//@Override
	public void onDestroy() {
		super.onDestroy();

		Log.d(TAG, "onDestroy");

		if (!sentResult){
			Intent returnIntent;
			returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
			returnIntent.putExtra("Result", "NORESULT");
			returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
			sendBroadcast(returnIntent);
		}	
	}

	// IL METODO onAttachedToWindow serve per disabilitare i tasti Home, Back e Menu
	/*@Override 
	public void onAttachedToWindow() {
		Log.d(TAG, "onAttachedToWindow ");
	    super.onAttachedToWindow();
	    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	}*/

	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		Log.d(TAG, "onKeyDown - keyCode " + keyCode);
		if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_MENU) || 
				(keyCode == KeyEvent.KEYCODE_SEARCH) || (keyCode == KeyEvent.KEYCODE_HOME))
			return true;
		return false;

	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		Log.d(TAG, "onKeyLongPress - keyCode " + keyCode);
		if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_MENU) || 
				(keyCode == KeyEvent.KEYCODE_SEARCH)|| (keyCode == KeyEvent.KEYCODE_HOME))
			return true;
		return false;
	}

	public int getOffset(){

		return offset;
	}

	public View getBaseView(){

		return baseView;
	}

	public void setA(int resId){
		A.setText(resId);
	}
	public void setB(int resId){
		B.setText(resId);
	}
	public void setC(int resId){
		C.setText(resId);
	}
	public void setD(int resId){
		D.setText(resId);
	}

	private void DefineButtonsRectangle(){

		ViewGroup centerBaseView = (ViewGroup) baseView.findViewById(R.id.center_base_view);

		int gap = A.getBottom() + centerBaseView.getBottom();
		offset = A.getBottom();

		ARect = new Rect(A.getLeft(), A.getTop(), A.getRight(), A.getBottom()); 
		BRect = new Rect(B.getLeft(), B.getTop(), B.getRight(), B.getBottom()); 
		CRect = new Rect(C.getLeft(), C.getTop() + gap, C.getRight(), C.getBottom() + gap); 
		DRect = new Rect(D.getLeft(), D.getTop() + gap, D.getRight(), D.getBottom() + gap); 

		//Log.d(TAG, "A " + A.getLeft() + " " + A.getTop() + " " + A.getRight()+ " " + A.getBottom());
		//Log.d(TAG, "B " + B.getLeft() + " " + B.getTop() + " " + B.getRight()+ " " + B.getBottom());
		//Log.d(TAG, "C " + C.getLeft() + " " + CRect.top + " " + C.getRight()+ " " + CRect.bottom);
		//Log.d(TAG, "D " + D.getLeft() + " " + DRect.top + " " + D.getRight()+ " " + DRect.bottom);

		//Log.d(TAG, "Base View " + baseView.getLeft() + " " + baseView.getTop()
		//		+ " " + baseView.getRight() + " " + baseView.getBottom());		
	}

	private Button InsideButton (int x, int y){

		//Log.d(TAG, "x " + x + " y " + y);

		if (ARect.contains(x, y))
			return A;
		if (BRect.contains(x, y))
			return B;
		if (CRect.contains(x, y))
			return C;
		if (DRect.contains(x, y))
			return D;

		return null;
	}

	// CLOSE -> ESC 
	public void onClick_A(){	
		Log.d(TAG, "onClick_A");
	}

	// POSITION
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
	}

	// REPEAT 
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
	}

	// DONE -> BACK
	public void onClick_D(){	
		Log.d(TAG, "onClick_D");
	}


	public void onClick_Center(int event, float X, float Y){	
		Log.d(TAG, "onClick_Center");
	}


	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(TAG, "onTouchEvent " + event.getAction());

		if (event.getAction() == MotionEvent.ACTION_CANCEL)
			return true;

		if (gestureDetector.onTouchEvent(event)) {
			return true;
		}
		// ATTENZIONE WORKAROUND INDECENTE SENNO' NON FUNZIONA
		if (event.getAction() == MotionEvent.ACTION_UP){
			Log.d(TAG, "onTouchEvent Dopo gestureDetector UP " + event.getAction());
			return true;
		}
		
		Log.d(TAG, "onTouchEvent  Dopo gestureDetector " + event.getAction());
		boolean b = gestureListener.onScroll(null, event, 0, 0);
		return true;	
		// ATTENZIONE WORKAROUND INDECENTE SENNO' NON FUNZIONA	
	}


	private class BaseViewListener implements OnTouchListener {

		public boolean onTouch(View v, MotionEvent event) {

			Log.d(TAG, "onTouch " + event.getAction());

			if (event.getAction() == MotionEvent.ACTION_CANCEL)
				return true;

			if (gestureDetector.onTouchEvent(event)) {
				return true;
			}
			
			// ATTENZIONE WORKAROUND INDECENTE SENNO' NON FUNZIONA
			if (event.getAction() == MotionEvent.ACTION_UP){
				Log.d(TAG, "onTouch Dopo gestureDetector UP " + event.getAction());
				if (configurationManager.getSelectionType().equals(getString(R.string.TTS_Config_SelectionType_Touch)))
					onScrollUp(event);
				return true;
			}
			
			Log.d(TAG, "onTouch  Dopo gestureDetector " + event.getAction());
			boolean b = gestureListener.onScroll(null, event, 0, 0);
			return true;	
			// ATTENZIONE WORKAROUND INDECENTE SENNO' NON FUNZIONA
		}
	}


	private boolean onScrollUp(MotionEvent event){

		Log.d(TAG, "onScrollUp");

		if (firstTime){
			DefineButtonsRectangle();
			firstTime = false;
		}

		String buttonName;
		Button currentButton = InsideButton((int)event.getRawX(), (int)event.getRawY());


		if (currentButton == null){
			lastButton = null;
			
			onClick_Center(GestureEvents.ONSCROLLUP, event.getRawX(), event.getRawY());
			passBy = false;
		} /*else {
			int buttonId = currentButton.getId();
			if (buttonId == R.id.view_A) {
				onClick_A();
			} else if (buttonId == R.id.view_B) {
				onClick_B();
			} else if (buttonId == R.id.view_C) {
				onClick_C();
			} else if (buttonId == R.id.view_D) {
				onClick_D();
			}
		}*/

		return true;
	}
	
	
	class MyGestureDetector extends SimpleOnGestureListener {

		@Override
		//Notified when a long press occurs with the initial on down MotionEvent that trigged it.
		public void onLongPress(MotionEvent e){
			Log.d(TAG, "onLongPress");
		}

		@Override
		//The user has performed a down MotionEvent and not performed a move or up yet.
		public void	onShowPress(MotionEvent e){	
			Log.d(TAG, "onShowPress");
		}

		@Override
		//Notified when a tap occurs with the up MotionEvent that triggered it.
		public boolean onSingleTapUp(MotionEvent e){
			Log.d(TAG, "onSingleTapUp");
			return true;
		}

		@Override
		//Notified when an event within a double-tap gesture occurs, including the down, move, and up events.
		public boolean onDoubleTapEvent(MotionEvent e){	
			Log.d(TAG, "onDoubleTapEvent");
			return true;
		}

		@Override
		//Notified when a single-tap occurs.
		public boolean onSingleTapConfirmed(MotionEvent e){
			Log.d(TAG, "onSingleTapConfirmed");
			return true;
		}

		@Override
		// NOTE: DO NOT REMOVE EVEN IF THE BODY IS EMPTY
		// Notified when a tap occurs with the down MotionEvent that triggered it.
		public boolean onDown(MotionEvent event){
			Log.d(TAG, "onDown");
			return true; 
		}


		@Override
		//Notified of a fling event when it occurs with the initial on down MotionEvent and the matching up MotionEvent.
		public boolean onFling(MotionEvent start, MotionEvent stop, float velocityX, float velocityY){
			Log.d(TAG, "onFling");

			onClick_Center(GestureEvents.ONFLING_START, start.getRawX(), start.getRawY());
			onClick_Center(GestureEvents.ONFLING_STOP, stop.getRawX(), stop.getRawY());
			return true;
		}

		@Override
		//Notified when a scroll occurs with the initial on down MotionEvent and the current move MotionEvent.
		public boolean onScroll(MotionEvent e1, MotionEvent event, float distanceX, float distanceY){

			Log.d(TAG, "onScroll");

			if (firstTime){
				DefineButtonsRectangle();
				firstTime = false;
			}

			String buttonName;
			Button currentButton = InsideButton((int)event.getRawX(), (int)event.getRawY());


			if (currentButton == null){
				lastButton = null;
				//Log.d(TAG, "***************** BASE ACTION_DOWN " + event.getRawX() + " " + event.getRawY());
				//Log.d(TAG, "***************** BASE ACTION_DOWN " + event.getX() + " " + event.getY());
				onClick_Center(GestureEvents.ONSCROLL, event.getRawX(), event.getRawY());
				passBy = false;
			} else {
				passBy = true;
				if ((lastButton == null) || ((lastButton.getId() != currentButton.getId()))){
					lastButton = currentButton;
					buttonName = currentButton.getText().toString();
					speechManager.say(buttonName, false, false);
					vibrator.vibrate(100);
				}
			}

			return true;
		}

		@Override
		//Notified when a double-tap occurs.
		public boolean onDoubleTap(MotionEvent event){
			Log.d(TAG, "onDoubleTap");

			Button currentButton;
			
			if (firstTime){
				DefineButtonsRectangle();
				firstTime = false;
			}

			if (lastButton == null)
				currentButton = InsideButton((int)event.getRawX(), (int)event.getRawY());
			else
				currentButton = lastButton;

			if (currentButton == null){
				//Log.d(TAG, "***************** BASE ACTION_DOWN " + event.getRawX() + " " + event.getRawY());
				//Log.d(TAG, "***************** BASE ACTION_DOWN " + event.getX() + " " + event.getY());
				onClick_Center(GestureEvents.ONDOUBLETAP, event.getRawX(), event.getRawY());

			} else {
				speechManager.say(currentButton.getText().toString(), true, true);
				int buttonId = currentButton.getId();
				if (buttonId == R.id.view_A) {
					onClick_A();
				} else if (buttonId == R.id.view_B) {
					onClick_B();
				} else if (buttonId == R.id.view_C) {
					onClick_C();
				} else if (buttonId == R.id.view_D) {
					onClick_D();
				}
			}
			lastButton = null;
			return true;
		}
	}
}